package com.henghai.zhenxuan.ui.page.raise;

import static com.henghai.zhenxuan.App.getOpenSDK;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.api.GetYingShiToken;
import com.henghai.zhenxuan.data.bean.HttpBean;
import com.henghai.zhenxuan.data.bean.RaiseBean;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.data.config.Const;
import com.henghai.zhenxuan.data.repository.DataRepository;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.RaiseListRequester;
import com.henghai.zhenxuan.ui.page.adapter.RaiseAdapter;
import com.henghai.zhenxuan.ui.yingshi.EZRealPlayActivity;
import com.henghai.zhenxuan.ui.yingshi.SdkInitParams;
import com.henghai.zhenxuan.ui.yingshi.SdkInitTool;
import com.henghai.zhenxuan.ui.yingshi.ServerAreasEnum;
import com.henghai.zhenxuan.utils.EZUtils;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.data.response.DataResult;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.videogo.constant.IntentConsts;
import com.videogo.exception.BaseException;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 饲养园
 */

public class RaiseFragment extends BaseFragment {
    private RaiseStates mStates;
    private RaiseListRequester mRaiseListRequester;
    private RefreshLayout mRefreshLayout;
    private RaiseAdapter adapter;
    private ListenerRefreshHandler mListenerRefreshHandler;
    private PageMessenger mMessenger;


    private static final String TAG = "RaiseFragment";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(RaiseStates.class);
        mRaiseListRequester = getFragmentScopeViewModel(RaiseListRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        adapter = new RaiseAdapter(getContext());
        adapter.setListener(new RaiseAdapter.OnItemBtClickListener() {
            @Override
            public void onItemMonitorClick(RaiseBean.RowsDTO bean) {
                DataRepository.getInstance().getYingShiToken(getViewLifecycleOwner(), new GetYingShiToken(), new DataResult.Result<HttpBean>() {
                    @Override
                    public void onResult(DataResult<HttpBean> dataResult) {
                        if (dataResult.getResult().getData() != null) {
                            Log.d(TAG, "onResult: " + dataResult.getResult().getData());
                            //查看监控
                            Log.d(TAG, "onItemMonitorClick: " + bean);
                            ServerAreasEnum mCurrentServerArea = ServerAreasEnum.getAllServers().get(0);
                            SdkInitParams sdkInitParams = SdkInitParams.createBy(mCurrentServerArea);
                            sdkInitParams.appKey = Const.YINGSHIAPPKEY;
                            sdkInitParams.token = (String) dataResult.getResult().getData();
                            sdkInitParams.openApiServer = Const.OPENAPISERVER;
                            sdkInitParams.openAuthApiServer = Const.OPENAUTHAPISERVER;
                            sdkInitParams.specifiedDevice = bean.getPetCode().equals("") ? "" : bean.getPetCode();
                            SdkInitTool.initSdk(getActivity().getApplication(), sdkInitParams);
                            GetMonitorCode monitorCode = new GetMonitorCode("BG3970259");
//                            GetMonitorCode monitorCode = new GetMonitorCode(bean.getPetCode());
                            monitorCode.execute();
                        }
                    }
                });
            }

            @Override
            public void onItmeFeedingClick(RaiseBean.RowsDTO bean) {
                //投喂
                mRaiseListRequester.setFeed(getViewLifecycleOwner(), AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "", bean.getPetId() + "");
            }
        });
        mListenerRefreshHandler = new ListenerRefreshHandler();
        return new DataBindingConfig(com.henghai.zhenxuan.R.layout.fragment_raise, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.listener, mListenerRefreshHandler)
                .addBindingParam(BR.loadListener, new ListenerLoadHandler())
                .addBindingParam(BR.adapter, adapter);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        networkListening();
        //获取饲养园列表
        mRaiseListRequester.requestRaiseList(getViewLifecycleOwner(), mStates.pageNum + "'", mStates.PageSize);
        //获取饲料数量
        mRaiseListRequester.getFeedCount(getViewLifecycleOwner());
        mMessenger.output(this, messages -> {
            if (messages.eventId == Messages.EVENT_ADOPT_PET) {//领养宠物成功
                //刷新列表
                mRefreshLayout.autoRefresh();
            } else if (messages.eventId == Messages.EVENT_SHOW_REWARD_AD_SUCCESS) {//监听激励广告查看完毕
                //直接获取饲料
                mRaiseListRequester.getFeed(getViewLifecycleOwner(), AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "");
            }
        });

    }

    private void networkListening() {
        //监听获取饲养园列表
        mRaiseListRequester.getRaiseListTaskResult().observe(getViewLifecycleOwner(), new Observer<DataResult<HttpBean<RaiseBean>>>() {
            @Override
            public void onChanged(DataResult<HttpBean<RaiseBean>> httpBeanDataResult) {
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMore();
                }
                if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                    TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                    return;
                }
                RaiseBean raiseBean = httpBeanDataResult.getResult().getData();
                mStates.rows = raiseBean.getRows().size();
                List<RaiseBean.RowsDTO> list = new ArrayList<>();
                list.addAll(mStates.taskList.get());
                list.addAll(raiseBean.getRows());
                mStates.taskList.set(list);
            }
        });

        //监听检查是否可以获取饲料
        mRaiseListRequester.getReceiveTaskResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {
            Log.d(TAG, "onCreate: " + httpBeanDataResult.getResponseStatus().getResponseCode());
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.WARNING);
                return;
            }
            Log.d(TAG, "onCreate: " + httpBeanDataResult.getResult().getData());
            if (httpBeanDataResult.getResult().getData().getFeedQuantityCanAcquire() > 0) {
                if (!httpBeanDataResult.getResult().getData().isCanAcquire()) {
                    TipDialog.show("请求过于频繁，请" + httpBeanDataResult.getResult().getData().getExpireData() + "后再试", WaitDialog.TYPE.WARNING);
                    return;
                }
                //调起激励广告
                if (Const.ISSHOWAD) {
                    mMessenger.input(new Messages(Messages.EVENT_SHOW_REWARD_AD));
                } else {
                    //直接获取饲料
                    WaitDialog.show("正在加载").setOnBackPressedListener(dialog -> {
                        dialog.dismiss();
                        return false;
                    });
                    mRaiseListRequester.getFeed(getViewLifecycleOwner(), AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "");
                }
            } else {
//                没有饲料了
                TipDialog.show("今日获取饲料数量为0", WaitDialog.TYPE.WARNING);
            }

        });
        //监听获取饲料接口
        mRaiseListRequester.getReceiveGetFeedResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {
            Log.d(TAG, "onCreate: " + httpBeanDataResult.getResult());
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.WARNING);
                return;
            }
            int feedCount = (Integer) httpBeanDataResult.getResult().getData();
            mStates.feedCount.set(String.valueOf(feedCount));
            TipDialog.show("饲料已添加", WaitDialog.TYPE.SUCCESS);
        });
        //监听投喂饲料
        mRaiseListRequester.getReceiveSetFeedResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {

            Log.d(TAG, "onCreate: " + httpBeanDataResult.getResponseStatus().getResponseCode());
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.WARNING);
                return;
            }
            int feedCount = (Integer) httpBeanDataResult.getResult().getData();
            mStates.feedCount.set(String.valueOf(feedCount));
            TipDialog.show("饲料已投喂", WaitDialog.TYPE.SUCCESS);
        });
        //监听获取饲料数量
        mRaiseListRequester.getReceivegetFeedCountResult().observe(getViewLifecycleOwner(), httpBeanDataResult -> {

            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.WARNING);
                return;
            }
            int feedCount = (Integer) httpBeanDataResult.getResult().getData();
            mStates.feedCount.set(String.valueOf(feedCount));
        });
    }

    public class ClickProxy {
        public void getFeed() {
            //查看是否可以获取饲料
            mRaiseListRequester.checkAcquire(getViewLifecycleOwner());

            //获取饲料
//            mRaiseListRequester.getFeed(getViewLifecycleOwner(), AppConfig.INSTANCE.getMConfigs().user().get().getUserId() + "");
        }

        public void test() {

        }
    }


    public class ListenerLoadHandler implements OnLoadMoreListener {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            mRefreshLayout = refreshLayout;
            if (mStates.rows >= Integer.parseInt(mStates.PageSize)) {
                mStates.pageNum++;
                mRaiseListRequester.requestRaiseList(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
            } else {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        }
    }

    public class ListenerRefreshHandler implements OnRefreshListener {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            mStates.pageNum = 1;
            mRefreshLayout = refreshLayout;
            mStates.taskList.set(new ArrayList<>());
            mRaiseListRequester.requestRaiseList(getViewLifecycleOwner(), mStates.pageNum + "", mStates.PageSize);
        }
    }

    public static class RaiseStates extends StateHolder {
        public int rows;
        public final String PageSize = "20";
        public final State<String> feedCount = new State<>("0");
        public int pageNum = 1;
        public final State<List<RaiseBean.RowsDTO>> taskList = new State<>(new ArrayList<>());
    }

    public class GetMonitorCode extends AsyncTask<Void, Void, List<EZDeviceInfo>> {
        private String deviceSerial;

        public GetMonitorCode(String deviceSerial) {
            this.deviceSerial = deviceSerial;
        }

        @Override
        protected List<EZDeviceInfo> doInBackground(Void... voids) {
            List<EZDeviceInfo> result = null;
            EZDeviceInfo info = null;
            try {
                info = getOpenSDK().getDeviceInfo(deviceSerial);
                final EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(info, 0);
                Log.d(TAG, "doInBackground: " + (info.getStatus() != 1));//设备是否在线
                if (cameraInfo != null) {
                    Intent intent = new Intent(getContext(), EZRealPlayActivity.class);
                    intent.putExtra(IntentConsts.EXTRA_CAMERA_INFO, cameraInfo);
                    intent.putExtra(IntentConsts.EXTRA_DEVICE_INFO, info);
                    startActivity(intent);
//                    startActivityForResult(intent, REQUEST_CODE);
                }
            } catch (BaseException e) {
                throw new RuntimeException(e);
            }
            Log.d(TAG, "onClickStartExperience: " + info.getDeviceSerial());
            return result;
        }
    }
}
